//
//  AccountRecordViewController.m
//  BTCoin
//
//  Created by Robin on 28/03/2018.
//  Copyright © 2018 Robin. All rights reserved.
//

#import "AccountRecordViewController.h"
#import <objc/runtime.h>
#import "AppUtil.h"
#import "UIAlertController+Block.h"
#import "CommonPickView.h"
#import "HooDatePicker.h"
#import "AccountRecordViewModel.h"
#import "TradeService.h"
#import "AccountRecordModel.h"
#import "AccountRecordTableCell.h"

static char saveParameterTag;

@interface AccountRecordViewController ()<UITableViewDataSource,UITableViewDelegate,HooDatePickerDelegate>
@property (nonatomic,weak) IBOutlet NSLayoutConstraint * viewTopConstraint;
@property (nonatomic,strong) IBOutletCollection(UIButton) NSArray * buttons;
@property (nonatomic,weak) IBOutlet UIButton * searchButton;
@property (nonatomic,weak) IBOutlet UILabel * emptyLabel;
@property (nonatomic,weak) IBOutlet UITableView * tableView;
@property (nonatomic, strong) CommonPickView * singlePickView;
@property (nonatomic, strong) HooDatePicker * dayBillDatePicker;
@property (nonatomic, strong) AccountRecordViewModel * viewModel;
@property(nonatomic,strong) AccountRecordModel * recordModel;
@end

@implementation AccountRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.viewTopConstraint.constant = NaviBarHeight+StatusBarHeight;
    [self setTitleText:@"账单明细"];
    self.automaticallyAdjustsScrollViewInsets = false;
    
    [self initUIHead];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initUIHead {
    UIButton * btn = [self getButtonByTag:0];
    [btn setTitle:PFTradeCodeArray[0] forState:UIControlStateNormal];
    
    NSString * dateStr = [AppUtil getStrWithDate:[NSDate new] format:@"yyyy-MM-dd"];
    btn = [self getButtonByTag:1];
    [btn setTitle:dateStr forState:UIControlStateNormal];
    
    btn = [self getButtonByTag:2];
    [btn setTitle:dateStr forState:UIControlStateNormal];
    self.viewModel.beginDate = dateStr;
    self.viewModel.endDate = dateStr;
    
    [self.searchButton setBackgroundImage:[UIImage imageWithColor:color_ffbd5b] forState:UIControlStateNormal];
    [self.searchButton setBackgroundImage:[UIImage imageWithColor:UIColorFromRGB(0xE5A649)] forState:UIControlStateHighlighted];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"AccountRecordTableCell" bundle:nil] forCellReuseIdentifier:@"AccountRecordTableCell"];
}

#pragma mark - event response
- (IBAction)clickSearchParameterContainerAction:(UIButton *)sender {
    [self showProxyPickerView:sender.tag];
}

- (void)showProxyPickerView:(NSInteger)tag {
    objc_setAssociatedObject(self, &saveParameterTag, @(tag), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    if (PFTradeProxyParameterCode == tag) {
        if (nil == self.singlePickView) {
            self.singlePickView = [[CommonPickView alloc] initWithFrame:Rect(0, 0, ScreenWidth, ScreenHeight) dataSource:[self.viewModel getSinglePickerViewDataSource:tag] parentView:self.view];
            @WeakObj(self)
            self.singlePickView.block = ^(NSString *stringValue) {
                @StrongObj(self)
                NSInteger t = [objc_getAssociatedObject(self, &saveParameterTag) integerValue];
                [self updateRequestModelValue:stringValue tag:t];
            };
        } else {
            [self.singlePickView updateDataSource:[self.viewModel getSinglePickerViewDataSource:tag]];
        }
        
        NSInteger rollIndex = [self originalIndex:tag];
        
        [self.singlePickView.pickerView selectRow:rollIndex inComponent:0 animated:YES];
        
        [self.singlePickView movePickerView];
    } else if (PFTradeProxyParameterStartDate == tag || PFTradeProxyParameterEndDate == tag) {
        if (nil == self.dayBillDatePicker) {
            [self createDayHooDatePicker];
        }
        
        NSDate * originalDate = [self originalDateByTag:tag];
        
        if (originalDate) {
            [self.dayBillDatePicker setDate:originalDate animated:YES];
        }
        
        [self.dayBillDatePicker show];
    }
}

- (IBAction)requestProxyRecordAction:(UIButton *)sender {
    Loading_Pig_Show(self.view);
    NSInteger controlIndex = [self originalIndex:PFTradeProxyParameterCode];
    NSArray * valueArray = PFTradeCodeValueArray[controlIndex];
    NSDictionary * parDict = @{@"recordType":valueArray[1],
                               @"symbol":valueArray[0],
                               @"currentPage":@(1),
//                               @"datetype":@(2),
                               @"begindate":self.viewModel.beginDate,
                               @"enddate":self.viewModel.endDate
                               };
    [[TradeService sharedTradeService] accountRecord:parDict success:^(id responseObject) {
        Loading_Hide(self.view);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            self.recordModel = [[AccountRecordModel alloc] initWithDictionary:responseObject error:nil];
            
            [self updateUI];
        }
    } fail:^(NSError *error) {
        Loading_Hide(self.view);
    }];
}

- (void)updateUI {
    self.emptyLabel.hidden = 0 < self.recordModel.list.count;
    self.tableView.hidden = 0 == self.recordModel.list.count;
    [self.tableView reloadData];
}

#pragma mark - HooDatePickerDelegate
- (void)datePicker:(HooDatePicker *)datePicker didSelectedDate:(NSDate*)date {
    if ([self checkChoseDate:date]) {
        NSInteger t = [objc_getAssociatedObject(self, &saveParameterTag) integerValue];
        [self selectDatePickerViewResponse:date tag:t];
    }
}

#pragma mark - private methods
- (void)updateRequestModelValue:(NSString *)key tag:(PFTradeProxyParameter)tag {
    if (PFTradeProxyParameterCode == tag) {
        UIButton * btn = [self getButtonByTag:tag];
        if (btn) {
            [btn setTitle:key forState:UIControlStateNormal];
        }
    }
}

- (UIButton *)getButtonByTag:(NSInteger)tag {
    for (UIButton * btn in self.buttons) {
        if (tag == btn.tag) {
            return btn;
        }
    }
    return nil;
}

- (void)createDayHooDatePicker {
    self.dayBillDatePicker = [[HooDatePicker alloc] initWithSuperView:self.view];
    self.dayBillDatePicker.delegate = self;
    self.dayBillDatePicker.datePickerMode = HooDatePickerModeDate;
    NSDateFormatter *dateFormatter = [NSDate shareDateFormatter];
    [dateFormatter setDateFormat:kDateFormatYYYYMMDD];
    NSDate *maxDate = [dateFormatter dateFromString:@"2020-01-01"];
    NSDate *minDate = [dateFormatter dateFromString:@"2015-01-01"];
    
    [self.dayBillDatePicker setDate:[NSDate date] animated:YES];
    self.dayBillDatePicker.minimumDate = minDate;
    self.dayBillDatePicker.maximumDate = maxDate;
}

- (NSDate *)originalDateByTag:(PFTradeProxyParameter)tag {
    NSDate * date = nil;
    UIButton * btn = [self getButtonByTag:tag];
    if (btn) {
        date = [AppUtil getDateWithStr:btn.currentTitle format:@"yyyy-MM-dd"];
    }
    
    return date;
}

- (NSInteger)originalIndex:(PFTradeProxyParameter)tag {
    UIButton * btn = [self getButtonByTag:tag];
    
    if (btn) {
        if (PFTradeProxyParameterCode == tag) {
            return [PFTradeCodeArray indexOfObject:btn.currentTitle];
        }
    }
    
    return 0;
}

- (BOOL)checkChoseDate:(NSDate *)date {
    if (NSOrderedDescending == [date compare:[NSDate date]]) {
        [UIAlertController createAlertViewWithTitle:@"" withViewController:self withCancleBtnStr:@"确定" withOtherBtnStr:nil withMessage:@"查询日期不能大于当前交易日" completionCallback:nil];
        
        return NO;
    }
    
    NSDate * startDate = nil;
    NSInteger tag = [objc_getAssociatedObject(self, &saveParameterTag) integerValue];
    if ( PFTradeProxyParameterEndDate == tag) {
        startDate = [self originalDateByTag:PFTradeProxyParameterStartDate];
    }
    
    if (NSOrderedDescending == [startDate compare:date]) {
        [UIAlertController createAlertViewWithTitle:@"" withViewController:self withCancleBtnStr:@"确定" withOtherBtnStr:nil withMessage:@"查询的开始日期不能大于结束日期" completionCallback:nil];
        
        return NO;
    }
    
    return YES;
}

- (void)selectDatePickerViewResponse:(NSDate *)date tag:(NSInteger)tag {
    NSString * showStr = [AppUtil getDateStringWithDate:date withFormat:@"yyyy-MM-dd"];
    UIButton * btn = [self getButtonByTag:tag];
    if (btn) {
        [btn setTitle:showStr forState:UIControlStateNormal];
    }
    
    if (PFTradeProxyParameterStartDate == tag) {
        self.viewModel.beginDate = showStr;
    } else if (PFTradeProxyParameterEndDate == tag) {
        self.viewModel.endDate = showStr;
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.recordModel.list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *ChannelIdentifier = @"AccountRecordTableCell";
    AccountRecordTableCell *cell = [tableView dequeueReusableCellWithIdentifier:ChannelIdentifier forIndexPath:indexPath];
    
    [self configCell:cell indexPath:indexPath];
    
    return cell;
}

- (void)configCell:(AccountRecordTableCell *)cell indexPath:(NSIndexPath *)indexPath {
//    ARecordDetailModel * detailModel = self.recordModel.list[indexPath.row/2];
//    NSDate * date = [[NSDate alloc] initWithTimeIntervalSince1970:detailModel.fcreatetime.time/1000.0];
//    cell.dateLabel.text = [date stringWithDateFormate:@"yyyy-MM-dd"];
//    if (0 == indexPath.row%2) {
//        cell.typeLabel.text = @"可用";
//        cell.CNYLabel.text = [NSString stringWithFormat:@"%@",detailModel.detail[@"0"][@"total"]];
//        cell.BTCLabel.text = [NSString stringWithFormat:@"%@",detailModel.detail[@"1"][@"total"]];
//        cell.LiteLabel.text = [NSString stringWithFormat:@"%@",detailModel.detail[@"12"][@"total"]];
//        cell.EtherLabel.text = [NSString stringWithFormat:@"%@",detailModel.detail[@"13"][@"total"]];
//        cell.EtherClassicLabel.text = [NSString stringWithFormat:@"%@",detailModel.detail[@"14"][@"total"]];
//    } else {
//        cell.typeLabel.text = @"冻结";
//        cell.CNYLabel.text = [NSString stringWithFormat:@"%@",detailModel.detail[@"0"][@"frozen"]];
//        cell.BTCLabel.text = [NSString stringWithFormat:@"%@",detailModel.detail[@"1"][@"frozen"]];
//        cell.LiteLabel.text = [NSString stringWithFormat:@"%@",detailModel.detail[@"12"][@"frozen"]];
//        cell.EtherLabel.text = [NSString stringWithFormat:@"%@",detailModel.detail[@"13"][@"frozen"]];
//        cell.EtherClassicLabel.text = [NSString stringWithFormat:@"%@",detailModel.detail[@"14"][@"frozen"]];
//    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 40.0;
}

#pragma mark - getter & setter
- (AccountRecordViewModel *)viewModel {
    if (nil == _viewModel) {
        _viewModel = [[AccountRecordViewModel alloc] init];
    }
    
    return _viewModel;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
